package org.example.springcloud.common;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

// 已手动加上getter/setter方法，防止报错 HttpMessageNotWritableException
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    private Integer code; //编码：200成功，其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //其他动态数据

    public static <T> Result<T> success() {
        Result<T> r = new Result<T>();
        r.code = 200;
        return r;
    }

    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<T>();
        r.data = data;
        r.code = 200;
        return r;
    }

    public static <T> Result<T> success(Integer code, T data) {
        Result<T> r = new Result<T>();
        r.data = data;
        r.code = code;
        return r;
    }

    public static Result<String> success(String format, Object... objects) {
        Result<String> r = new Result<>();
        r.code = 200;
        r.msg = StrUtil.format(format, objects);
        return r;
    }

    public static <T> Result<T> error(String format, Object... objects) {
        Result  r = new Result<>();
        r.code = 400;
        r.msg = StrUtil.format(format, objects);
        return r;
    }

    // 泛型方法
    public static <T> Result<T> error(String msg) {
        Result r = new Result();
        r.msg = msg;
        r.code = 400;
        return r;
    }

    public Result<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }
}